﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace CommHelper
{
    public class HttpWebHelper
    {
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="para">请求内容</param>
        /// <param name="encoding">解析编码</param>
        /// <returns></returns>
        public static string RequestGet(string url, Dictionary<string, string> para, Encoding encoding, string token = "")
        {
            string result = string.Empty;
            if (encoding == null)
                encoding = Encoding.GetEncoding("gb2312");

            if (para != null)
            {
                url = url + "?";
                foreach (var item in para)
                {
                    url += item.Key + "=" + item.Value + "&";
                }
                url.TrimEnd('&');
            }

            result = RequestGet(url, encoding, token);

            return result;
        }

        public static string RequestGet(string url, string content, Encoding encoding, string token = "")
        {
            return RequestGet(url + "?" + content, encoding, token);
        }

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">完整的URL</param>
        /// <param name="encoding"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string RequestGet(string url, Encoding encoding, string token = "")
        {
            string result = string.Empty;
            if (encoding == null)
                encoding = Encoding.GetEncoding("gb2312");
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = "GET";
                httpWebRequest.ContentType = "application/json";
                if (token != "")
                {
                    httpWebRequest.Headers.Add("Authorization", string.Format("BasicAuth {0}", token));
                }
                //请求并接收返回内容
                HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, encoding);
                result = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="para">请求内容</param>
        /// <param name="encoding">解析编码</param>
        /// <returns></returns>
        public static string RequestPost(string url, Dictionary<string, string> para, Encoding encoding, string token = "", string type = "POST")
        {
            string result = string.Empty;
            if (para != null)
            {
                string context = "";
                foreach (var item in para)
                {
                    context += item.Key + "=" + item.Value + "&";
                }
                url.TrimEnd('&');

                result = RequestPost(url, context, encoding, token, type);
            }

            return result;
        }

        public static string RequestPost(string url, string context, Encoding encoding, string token = "", string type = "POST")
        {
            return RequestPost(url, Encoding.UTF8.GetBytes(context), encoding, token, type);
        }

        public static string RequestPost<T>(string url, T t, Encoding encoding, string token = "", string type = "POST")
        {
            string result = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            //result = "\"" + result.Replace("\"", "\\\"") + "\"";
            return RequestPost(url, result, encoding, token, type);
        }

        public static string RequestPost(string url, byte[] bytes, Encoding encoding, string token = "", string type = "POST")
        {
            string result = string.Empty;
            if (encoding == null)
                encoding = Encoding.GetEncoding("gb2312");

            try
            {
                // 设置请求的相关参数
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = type;
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.ContentLength = bytes.Length;
                httpWebRequest.AllowAutoRedirect = false;
                httpWebRequest.Timeout = 30 * 1000;
                if (token != "")
                {
                    httpWebRequest.Headers.Add("Authorization", string.Format("BasicAuth {0}", token));
                }
                //请求数据
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                //请求并接收返回内容
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream streamGet = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamGet, encoding);
                result = streamReader.ReadToEnd();
                streamGet.Close();
                httpWebResponse.Close();
            }
            catch (Exception e)
            {
                //CommHelper.LogHelper4net.LogInfo(CommData.Log4NetType.Error, "", e.Message, e);
                throw;
            }

            return result;
        }
    }
}